package com.bw.lib_common.fps

import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.Choreographer

class FpsMonitor private constructor() {

    // 配置参数
    private var monitorIntervalMs = 1000L    // 计算窗口时长（默认1秒）
    private var maxIntervalMs = 1000L        // FPS单位时间（默认1秒，即fps/s）
    private var frameCount = 0               // 当前窗口帧数
    private var lastFrameTimeNs = 0L         // 上一帧时间戳（纳秒）
    private val handler = Handler(Looper.getMainLooper())
    private var isMonitoring = false

    // 帧回调
    private val frameCallback = object : Choreographer.FrameCallback {
        override fun doFrame(frameTimeNs: Long) {
            if (!isMonitoring) return

            if (lastFrameTimeNs == 0L) {
                lastFrameTimeNs = frameTimeNs
            } else {
                val intervalNs = frameTimeNs - lastFrameTimeNs
                when {
                    intervalNs <= 0 -> reset()  // 处理异常时间差
                    intervalNs > monitorIntervalMs * 1_000_000 -> {
                        calculateAndLogFps(intervalNs)
                        reset()
                        lastFrameTimeNs = frameTimeNs
                    }
                    else -> frameCount++
                }
            }
            Choreographer.getInstance().postFrameCallback(this)
        }
    }

    // 计算并打印FPS
    private fun calculateAndLogFps(intervalNs: Long) {
        val fps = (frameCount * 1_000_000_000.0 / intervalNs) * (maxIntervalMs / 1000.0)
        handler.post { Log.d("FpsMonitor", "Current FPS: ${"%.1f".format(fps)}") }
    }

    // 重置计数器
    private fun reset() {
        frameCount = 0
        lastFrameTimeNs = 0L
    }

    // 开始监控
    fun start(intervalMs: Long = monitorIntervalMs) {
        if (isMonitoring) return
        monitorIntervalMs = intervalMs
        isMonitoring = true
        Choreographer.getInstance().postFrameCallback(frameCallback)
    }

    // 停止监控
    fun stop() {
        isMonitoring = false
        reset()
        Choreographer.getInstance().removeFrameCallback(frameCallback)
    }

    companion object {
        // 单例模式（可选）
        val instance by lazy { FpsMonitor() }
    }
}
